package com.kailong.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class InkImageUtil {
    public static String uploadImg(String fileName,InputStream inputStream) throws IOException {
            // 设置上传地址
            URL url = new URL("https://img.ink/api/upload");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置请求方法为POST
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            // 设置请求头
            connection.setRequestProperty("token", "f3ee57bcc8d796ea9b72bd776f243d98"); // 替换为你的token
            // 构建请求参数
            String boundary = Long.toHexString(System.currentTimeMillis());
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            OutputStream output = connection.getOutputStream();
            PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"), true);
            // 添加图片参数
            writer.append("--" + boundary).append("\r\n");
            writer.append("Content-Disposition: form-data; name=\"image\"; filename=\"" + fileName + "\"").append("\r\n");
            writer.append("Content-Type: image/jpeg").append("\r\n");
            writer.append("\r\n");
            writer.flush();
            // 读取图片内容并写入请求
            InputStream input = inputStream;
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = input.read(buffer)) != -1) {
                output.write(buffer, 0, bytesRead);
            }
            output.flush();
            input.close();
            // 结束请求
            writer.append("\r\n").append("--" + boundary + "--").append("\r\n");
            writer.close();
            // 获取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line;
                StringBuffer response = new StringBuffer();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                System.out.println(response.toString());
                ObjectMapper mapper = new ObjectMapper();
                JsonNode rootNode = mapper.readTree(String.valueOf(response));
                JsonNode userNode = rootNode.path("data");
                String imgUrl = userNode.path("url").asText();
                return imgUrl;
            } else {
                return "error";
            }
    }
}
